#include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010, M = 1e6 + 10;
bool maze[N][N];
int mapnum = 0;
// map数组保存每个节点属于哪个连通图
int map[N][N];
int cnt[M];
int n, m;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};

bool is_true(int x, int y)
{
    if (x && !y)
        return true;
    if (!x && y)
        return true;
    return false;
}

void dfs(int x, int y)
{
    if (map[x][y])
        return;
    map[x][y] = ++mapnum;
    queue<PII> q;
    q.push({x, y});
    int num = 1;
    while (q.size())
    {
        auto e = q.front();
        q.pop();
        int a = e.first, b = e.second;
        for (int i = 0; i < 4; ++i)
        {
            int aa = a + dx[i], bb = b + dy[i];
            if (aa >= 0 && aa < n && bb >= 0 && bb < n && is_true(maze[a][b], maze[aa][bb]) && !map[aa][bb])
            {
                map[aa][bb] = mapnum;
                ++num;
                q.push({aa, bb});
            }
        }
    }
    cnt[mapnum] = num;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    char s;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
        {
            cin >> s;
            maze[i][j] = s - '0';
        }
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            dfs(i, j);
    while (m--)
    {
        int a, b;
        cin >> a >> b;
        cout << cnt[map[a - 1][b - 1]] << endl;
    }
    return 0;
}
